package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.system.domain.TbCar;

/**
 * 车辆Controller
 * 
 * @author ruoyi
 * @date 2023-06-23
 */
@RestController
@RequestMapping("/car")
@Api(tags = "测试swagger")
public class TbCarController extends BaseController
{
    @Autowired
    private ITbCarService tbCarService;

    @Autowired
    private ITbCarTypeService tbCarTypeService;

    @Autowired
    private ITbMotorService tbMotorService;

    @Autowired
    private ITbCellService tbCellService;

    @Autowired
    private ITbRailService tbRailService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 查询车辆列表
     */
    @RequiresPermissions("system:car:list")
    @GetMapping("/list")
    public TableDataInfo list(TbCar tbCar) throws IOException {
        startPage();
        List<TbCar> list = tbCarService.selectTbCarList(tbCar);

        for (TbCar car:list){
            IndexRequest indexRequest=new IndexRequest("tb_car").id(car.getCarId()+"");
            indexRequest.source(JSON.toJSONString(car), XContentType.JSON);
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        }

        SearchRequest searchRequest=new SearchRequest("tb_car");
        //设置高亮
        searchRequest.source().highlighter(new HighlightBuilder().field("carVin"));
//        searchRequest.source().sort("catId", SortOrder.ASC);
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if (StringUtils.isNotBlank(tbCar.getCarVin())){
            boolQuery.must(QueryBuilders.matchQuery("carVin", tbCar.getCarVin()));
        }
        if (StringUtils.isNotBlank(tbCar.getCarTypeName())){
            boolQuery.must(QueryBuilders.matchQuery("carTypeName", tbCar.getCarTypeName()));
        }
        searchRequest.source().query(boolQuery);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        long total= search.getHits().getTotalHits().value;
        SearchHit[] hits = search.getHits().getHits();
        List<TbCar> carList=new ArrayList<>();
        for (SearchHit hit:hits){
            String string = hit.getSourceAsString();
            TbCar tbCar1 = JSON.parseObject(string, TbCar.class);
            HighlightField carVin = hit.getHighlightFields().get("carVin");

            if (carVin!=null){
                String s = carVin.getFragments()[0].toString();
                tbCar1.setCarVin(s);
            }
            carList.add(tbCar1);
        }


        return getDataTables(carList,total);
    }

    /**
     * 查询车辆列表2
     */
    @RequiresPermissions("system:car:getCarList")
    @GetMapping("/getCarList")
    public TableDataInfo getCarList(TbCar tbCar)
    {
        startPage();
        List<TbCar> list = tbCarService.selectTbCarList(tbCar);
        return getDataTable(list);
    }

    /**
     * 导出车辆列表
     */
    @RequiresPermissions("system:car:export")
    @Log(title = "车辆", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbCar tbCar)
    {
        List<TbCar> list = tbCarService.selectTbCarList(tbCar);
        ExcelUtil<TbCar> util = new ExcelUtil<TbCar>(TbCar.class);
        util.exportExcel(response, list, "车辆数据");
    }

    /**
     * 获取车辆详细信息
     */
    @RequiresPermissions("system:car:query")
    @GetMapping(value = "/{carId}")
    public AjaxResult getInfo(@PathVariable("carId") Long carId)
    {
        return success(tbCarService.selectTbCarByCarId(carId));
    }

    /**
     * 新增车辆
     */
    @RequiresPermissions("system:car:add")
    @Log(title = "车辆", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbCar tbCar)
    {
        return toAjax(tbCarService.insertTbCar(tbCar));
    }

    /**
     * 修改车辆
     */
    @RequiresPermissions("system:car:edit")
    @Log(title = "车辆", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbCar tbCar)
    {
        return toAjax(tbCarService.updateTbCar(tbCar));
    }

    /**
     * 删除车辆
     */
    @RequiresPermissions("system:car:remove")
    @Log(title = "车辆", businessType = BusinessType.DELETE)
	@DeleteMapping("/{carIds}")
    public AjaxResult remove(@PathVariable Long[] carIds)
    {
        return toAjax(tbCarService.deleteTbCarByCarIds(carIds));
    }

    /**
     * 查询车辆类型列表
     */
    @RequiresPermissions("system:car:typeList")
    @GetMapping("/typeList")
    public TableDataInfo typeList()
    {
        List<TbCarType> list = tbCarTypeService.selectTbCarTypeList();
        return getDataTable(list);
    }

    /**
     * 查询车辆电机列表
     */
    @RequiresPermissions("system:car:motorList")
    @GetMapping("/motorList")
    public TableDataInfo motorList()
    {
        List<TbMotor> list = tbMotorService.selectTbMotorList();
        return getDataTable(list);
    }

    /**
     * 查询车辆电池列表
     */
    @RequiresPermissions("system:car:cellList")
    @GetMapping("/cellList")
    public TableDataInfo cellList()
    {
        List<TbCell> list = tbCellService.selectTbCellList();
        return getDataTable(list);
    }

    /**
     * 查询电子围栏
     */
    @RequiresPermissions("system:car:railList")
    @GetMapping("/railList")
    public TableDataInfo railList()
    {
        List<TbRail> list = tbRailService.selectTbRailList();
        return getDataTable(list);
    }
    @PostMapping(value = "/knife4jTest")
    @ApiImplicitParam(name = "name",value = "姓名",required = true)
    @ApiOperation("测试")
    public String sayHello(@RequestParam("name") String name) {
        return "test:" + name;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送数据
     */
    @RequiresPermissions("system:car:sendSj")
    @GetMapping("/sendSj")
    public Integer sendSj()
    {
        redisTemplate.opsForValue().set("sendSj","true",2, TimeUnit.MINUTES);
        return 100;
    }

    /**
     * 停止发送数据
     */
    @RequiresPermissions("system:car:sendSj2")
    @GetMapping("/sendSj2")
    public Integer sendSj2()
    {
        redisTemplate.opsForValue().set("sendSj","false");
        return 200;
    }

    @RequiresPermissions("system:car:getSj")
    @GetMapping("/getSj")
    public Integer getSj()
    {
        String sendSj = redisTemplate.opsForValue().get("sendSj");
        if (sendSj!=null){
            if (sendSj.equals("true")){
                return 100;
            }
            redisTemplate.delete("sendSj");
        }
        return 200;
    }




}
